var express = require('express');
var router = express.Router();
var PW = require("png-word");
var R = require("random-word");
var pw = new PW();
var fs = require("fs");

/* GET users listing. */
// router.get('/', function(req, res, next) {
//   // res.send('respond with a resource');
//   res.locals.user = req.session.user || "";
//   res.locals.firstnum = Math.round(Math.random()*10);
//   res.locals.secondnum = Math.round(Math.random()*10);
//   render("message");
// });=
var users = require("./user.json");
// var users = {};
router.post('/login', function(req, res){
  const {
    loginname,
     password,
       vnum
     } = req.body;
     if(users[loginname] &&
       users[loginname].password === password &&
       req.session.firstnum+req.session.secondnum === Number(vnum)
     ){
        req.session.user = {loginname};
     }
     console.log(loginname,password,vnum,req.session.firstnum,req.session.secondnum,req.session.user);
     res.redirect("back");
});

router.get("/logout", function(req, res){
  req.session.user = null;
  res.redirect("back");
});

router.post("/register", function(req, res){
  const{
    loginname,
    password,
    confirm,
    vimg
  } = req.body;
  if(req.session.regVimg === vimg && loginname && password && password === confirm){
    users[loginname] = {loginname, password};
    fs.writeFileSync(__dirname+"/user.json", JSON.stringify(users));
  }
  console.log(loginname, password,confirm,vimg,req.session.regVimg,users[loginname]);
  res.redirect("back");
});

router.get("/vimg", function(req, res){
  var r = new R("1234567890");
  req.session.regVimg = r.random(5);
  pw.createReadStream(req.session.regVimg).pipe(res);
});

function isLogined(req, res, next){

}
var messages = require("./message.json");
router.post("/sendmsg", function(req, res){
  const messagetext = req.body.message;
  const message = {
    username:req.session.user,
    text:messagetext
  };
  messages.push(message);
  fs.writeFileSync(__dirname+"/message.json", JSON.stringify(messages));
  res.redirect("back");
});

module.exports = router;
